// 忘记密码相关路由配置

const Router = require('@koa/router');
const mongoose = require('mongoose');
const config = require('../../project.config');
const ForgetPasswordModel = mongoose.model('ForgetPassword');
const UserModel = mongoose.model('User');

const router = new Router({
  prefix: '/forget-password',
});

// 忘记密码列表接口
router.get('/list', async (ctx) => {
  console.log('--> 调用接口 get /forget-password/list');
  let { page, size } = ctx.query;
  page = Number(page);
  size = Number(size);
  const list = await ForgetPasswordModel.find({ status: 1 })
    .skip((page - 1) * size)
    .limit(size)
    .sort({ _id: -1 })
    .exec();
  const total = await ForgetPasswordModel.find({ status: 1 }).countDocuments().exec();
  ctx.body = {
    msg: '获取忘记密码列表成功',
    code: 1,
    data: {
      list,
      total,
    },
  };
});

// 添加忘记密码申请接口
router.post('/add', async (ctx) => {
  console.log('--> 调用接口 post /forget-password/add');
  const { username } = ctx.request.body;
  const findone = await ForgetPasswordModel.findOne({ username, status: 1 }).exec();
  if (findone) {
    ctx.body = {
      msg: '已经申请',
      code: 1,
      data: null,
    };
    return;
  }
  const forget = new ForgetPasswordModel({
    username,
    status: 1,
  });
  await forget.save();
  ctx.body = {
    msg: '申请成功',
    code: 1,
    data: null,
  };
});

// 忘记密码请求状态修改 接口
router.post('/update/status', async (ctx) => {
  console.log('--> 调用接口 post /forget-password/update/status');
  const { id, status } = ctx.request.body;
  const one = await ForgetPasswordModel.findOne({ _id: id }).exec();
  one.status = status;
  if (status === 2) {
    const user = await UserModel.findOne({ _id: id }).exec();
    user.password = config.DEFAULT_PASSWORD;
  }
  await one.save();
  ctx.body = {
    msg: '状态修改成功',
    code: 1,
    data: null,
  };
});

module.exports = router;
